﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using Saplin.Controls;

public partial class DuAn : System.Web.UI.Page
{
    SqlParameter[] p;
    clsXuLy ex = new clsXuLy();
    DataTable dt;
    string frmName = "frmDuAn";
    static int STT = 0;
    public string Header = System.Configuration.ConfigurationSettings.AppSettings["Header"].ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Title = "Quản lý dự án | " + Header;
            btnCancel_Click(sender, e);
            
        }

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            p = new SqlParameter[5];
            p[0] = new SqlParameter("@IDs", Guid.NewGuid());
            p[0].SqlDbType = SqlDbType.UniqueIdentifier;
            p[1] = new SqlParameter("@MaDuAn", txtMaDA.Text.Trim());
            p[1].SqlDbType = SqlDbType.NVarChar;
            p[2] = new SqlParameter("@TenDuAn", txtTenDuAn.Text.Trim());
            p[2].SqlDbType = SqlDbType.NVarChar;
            p[3] = new SqlParameter("@ChuDauTu", txtChuDauTu.Text.Trim());
            p[3].SqlDbType = SqlDbType.NVarChar;
            p[4] = new SqlParameter("@DiaDiem", txtDiaDiem.Text.Trim());
            p[4].SqlDbType = SqlDbType.NVarChar;
            ex.ExecuteNonQuerry("sp_vnttblduan_Add", p);
            btnCancel_Click(sender, e);

            int s = ex.GetValueInt_Text("select count(*) from vnttblautonumber where upper(Name)='" + frmName.ToUpper() + "'");
            if (s.Equals(0))
            {
                //Insert auto number
                p = new SqlParameter[3];
                p[0] = new SqlParameter("@IDs", Guid.NewGuid());
                p[0].SqlDbType = SqlDbType.UniqueIdentifier;
                p[1] = new SqlParameter("@Name", frmName);
                p[1].SqlDbType = SqlDbType.VarChar;
                p[2] = new SqlParameter("@Number", 1);
                p[2].SqlDbType = SqlDbType.Int;
                ex.ExecuteNonQuerry("sp_vnttblautonumber_Add", p);
            }
            else
            {
                //Update auto number
                p = new SqlParameter[2];
                p[0] = new SqlParameter("@Name", frmName);
                p[0].SqlDbType = SqlDbType.VarChar;
                p[1] = new SqlParameter("@Number", txtMaDA.Text.Trim().Substring(6));
                p[1].SqlDbType = SqlDbType.Int;
                ex.ExecuteNonQuerry("sp_vnttblautonumber_Update", p);
            }
            btnCancel_Click(sender, e);
            gstGetMess("Lưu thành công", "");
        }
        catch (Exception ax)
        {
            gstGetMess("Có lỗi trong quá trình lưu, xem trong file log", "");
            ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tDự án\t" + ax.Message);
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        txtMaDA.Text = "";
        txtTenDuAn.Text = "";
        txtDiaDiem.Text = "";
        txtChuDauTu.Text = "";
        txtTenDuAn.Focus();

        btnSave.Visible = true;
        btncapnhat.Visible = false;
        GV.DataSource = ex.GetData("sp_vnttblduan_ListGridView");
        GV.DataBind();

        STT = ex.GetValueInt_Text("select count(*) from vnttblautonumber where upper(Name)='" + frmName.ToUpper() + "'");

        if (STT.Equals(0))
            STT++;
        else
            STT = ex.GetValueInt_Text("select isnull(Number,0) from vnttblautonumber where upper(name)='" + frmName.ToUpper() + "'") + 1;

        if (STT < 10)
            txtMaDA.Text = DateTime.Now.ToString("yyMMdd") + "0" + STT.ToString();
        else txtMaDA.Text = DateTime.Now.ToString("yyMMdd") + STT.ToString();

        FirstGridViewRow();

        
    }
    private void gstGetMess(string gstMess, string gstLink)
    {
        if (gstLink == "")
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "')", true);
        else
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), " ", "alert('" + gstMess + "');window.location.href='" + gstLink + "'", true);

    }
    protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        string ID = e.CommandArgument.ToString();
        hdID.Value = ID;
        Guid gID = new Guid(ID);
        p = new SqlParameter[1];
        p[0] = new SqlParameter("@IDs", gID);
        p[0].SqlDbType = SqlDbType.UniqueIdentifier;

        if (e.CommandName.Equals("Select"))
        {
            DataTable dt = ex.GetData("sp_vnttblduan_ListByID", p);
            if (dt.Rows.Count > 0)
            {
                try
                {
                    txtMaDA.Text = dt.Rows[0]["MaDuAn"].ToString();
                    txtTenDuAn.Text = dt.Rows[0]["TenDuAn"].ToString();
                    txtDiaDiem.Text = dt.Rows[0]["DiaDiem"].ToString();
                    txtChuDauTu.Text = dt.Rows[0]["ChuDauTu"].ToString();
                }
                catch (Exception ax)
                {
                    gstGetMess("Có lỗi trong quá trình xem chi tiết, xem trong file log", "");
                    ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tDự án\t" + ax.Message);
                }

            }
            btncapnhat.Visible = true;
            btnSave.Visible = false;
        }
        else
            if (e.CommandName.Equals("Del"))
            {

                try
                {
                    ex.ExecuteNonQuerry("sp_vnttblduan_Del", p);
                    btnCancel_Click(sender, e);
                    gstGetMess("Xóa thành công", "");
                }
                catch (Exception ax)
                {
                    gstGetMess("Có lỗi trong quá trình xóa, xem trong file log", "");
                    ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tDự án\t" + ax.Message);

                }

            }
    }
    protected void btncapnhat_Click(object sender, EventArgs e)
    {
        try
        {
            Guid gID = new Guid(hdID.Value);
            p = new SqlParameter[4];
            p[0] = new SqlParameter("@IDs", gID);
            p[0].SqlDbType = SqlDbType.UniqueIdentifier;

            p[1] = new SqlParameter("@TenDuAn", txtTenDuAn.Text.Trim());
            p[1].SqlDbType = SqlDbType.NVarChar;
            p[2] = new SqlParameter("@ChuDauTu", txtChuDauTu.Text.Trim());
            p[2].SqlDbType = SqlDbType.NVarChar;
            p[3] = new SqlParameter("@DiaDiem", txtDiaDiem.Text.Trim());
            p[3].SqlDbType = SqlDbType.NVarChar;
            ex.ExecuteNonQuerry("sp_vnttblduan_Update", p);
            btnCancel_Click(sender, e);
            gstGetMess("Cập nhật thành công", "");
        }
        catch (Exception ax)
        {
            gstGetMess("Có lỗi trong quá trình cập nhật, xem trong file log", "");
            ex.WriteLog(Server.MapPath("Log.txt"), DateTime.Now.ToString() + "\tDự án\t" + ax.Message);
        }
    }

    private void FirstGridViewRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("NhaThau", typeof(string)));
        //dt.Columns.Add(new DataColumn("GoiThau", typeof(List<ListItem>)));
        dt.Columns.Add(new DataColumn("GoiThau", typeof(string)));
        dt.Columns.Add(new DataColumn("KySu", typeof(string)));
        dt.Columns.Add(new DataColumn("TuVan", typeof(string)));

        //List<ListItem> l = new List<ListItem>();

        //DataTable dt1 = ex.GetNhaThau();
        //for (int i = 0; i < dt1.Rows.Count; i++)
        //{
        //    l.Add(new ListItem() { Text = dt1.Rows[i][1].ToString(), Value = "1",Selected=true });
        //}
        //DataSource='<%#Eval("GoiThau") %>'
        
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["NhaThau"] = string.Empty;
        dr["GoiThau"] = string.Empty;
        dr["KySu"] = string.Empty;
        dr["TuVan"] = string.Empty;
        dt.Rows.Add(dr);

        ViewState["CurrentTable"] = dt;

        
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    private void AddNewRow()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    DropDownList dlNhaThau = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("dlNhaThau");
                    DropDownCheckBoxes dlGoiThau = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[2].FindControl("dlGoiThau");
                    DropDownCheckBoxes dlKySu = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[3].FindControl("dlKySu");
                    DropDownCheckBoxes dlTuVanTruong = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[4].FindControl("dlTuVanTruong");

                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i - 1]["NhaThau"] = dlNhaThau.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["GoiThau"] = dlGoiThau.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["KySu"] = dlKySu.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["TuVan"] = dlTuVanTruong.SelectedValue;
                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                GridView1.DataSource = dtCurrentTable;
                GridView1.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousData();
    }
    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DropDownList dlNhaThau = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("dlNhaThau");
                    DropDownCheckBoxes dlGoiThau = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[2].FindControl("dlGoiThau");
                    DropDownCheckBoxes dlKySu = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[3].FindControl("dlKySu");
                    DropDownCheckBoxes dlTuVanTruong = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[4].FindControl("dlTuVanTruong");


                    GridView1.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                    
                    
                    dlNhaThau.SelectedValue = dt.Rows[i]["NhaThau"].ToString();
                    dlGoiThau.SelectedValue = dt.Rows[i]["GoiThau"].ToString();
                    dlKySu.SelectedValue = dt.Rows[i]["KySu"].ToString();
                    dlTuVanTruong.SelectedValue = dt.Rows[i]["TuVan"].ToString();
                    rowIndex++;
                }
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        AddNewRow();
    }
    void GetDropCheckbox()
    {
        List<String> ID = new List<string>();
        List<String> Name = new List<string>();
        string kq = "", name = "";
        foreach (ListItem item in dlNhanVienThamGiaDuAn.Items)
        {
            if (item.Selected)
            {
                ID.Add(item.Value);
                Name.Add(item.Text);
                kq += item.Value + ",";
                name += item.Text;
            }
            //lblCountryName.Text = "Country Name: " + String.Join(",", CountryName_list.ToArray());
        }

        gstGetMess(name, "");
    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        //SetRowData();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            int rowIndex = Convert.ToInt32(e.RowIndex);
            if (dt.Rows.Count > 1)
            {
                dt.Rows.Remove(dt.Rows[rowIndex]);
                drCurrentRow = dt.NewRow();
                ViewState["CurrentTable"] = dt;
                GridView1.DataSource = dt;
                GridView1.DataBind();

                for (int i = 0; i < GridView1.Rows.Count - 1; i++)
                {
                    GridView1.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                }
                SetPreviousData();
            }
        }
    }
    private void SetRowData()
    {
        //int rowIndex = 0;

        //if (ViewState["CurrentTable"] != null)
        //{
        //    DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
        //    DataRow drCurrentRow = null;
        //    if (dtCurrentTable.Rows.Count > 0)
        //    {
        //        for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
        //        {
        //            DropDownList dlNhaThau = (DropDownList)GridView1.Rows[rowIndex].Cells[1].FindControl("dlNhaThau");
        //            DropDownCheckBoxes dlGoiThau = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[2].FindControl("dlGoiThau");
        //            DropDownCheckBoxes dlKySu = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[3].FindControl("dlKySu");
        //            DropDownCheckBoxes dlTuVanTruong = (DropDownCheckBoxes)GridView1.Rows[rowIndex].Cells[4].FindControl("dlTuVanTruong");


        //            drCurrentRow = dtCurrentTable.NewRow();
        //            drCurrentRow["RowNumber"] = i + 1;
        //            dtCurrentTable.Rows[i - 1]["TenVPP"] = txtTen.Text.Trim();
        //            dtCurrentTable.Rows[i - 1]["QuyCach"] = txtQuyCach.Text.Trim();
        //            dtCurrentTable.Rows[i - 1]["DVT"] = txtDVT.Text.Trim();
        //            dtCurrentTable.Rows[i - 1]["SLDN"] = txtSLDN.Text.Trim();
        //            dtCurrentTable.Rows[i - 1]["SLDuyet"] = txtSLDuyet.Text.Trim();
        //            dtCurrentTable.Rows[i - 1]["GhiChu"] = txtGhiChu.Text.Trim();
        //            rowIndex++;
        //        }

        //        ViewState["CurrentTable"] = dtCurrentTable;
        //    }
        //}
        //else
        //{
        //    Response.Write("ViewState is null");
        //}
    }
}